<?php

// 检查短信码
// PUT sms.checkCode

namespace app\api\resource\sms;
use think\Loader;
use think\Session;

class CheckCode
{
    // 方法
    public $_method = ['PUT'];
    // 前置
    public $_pre    = [];
    // 描述
    public $_description = '检查短信码';
    // 参数
    public $_param  = [
        'mobile' => '手机号',
        'code'   => '短信码',
    ];
    // 返回
    public $_return = [
        201 => '校验成功',
        422 => '请求参数不合法',
        400 => '未发送短信码|接收短信码手机号与校验手机号不相同|短信码不正确',
    ];

    public function run(&$request)
    {
        $params['mobile'] = $request->put('mobile/s','','trim');
        $params['code']   = $request->put('code/d',null,'abs');

        $validate = Loader::validate('Sms');
        if ( !$validate->scene('checkCode')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $sms = Session::get('sms');

        if ( !$sms ) return [400,'未发送短信码'];

        if ($sms['mobile'] != $params['mobile']) {
            return [400,'接收短信码手机号与校验手机号不相同'];
        } elseif ($sms['code'] != $params['code']) {
            return [400,'短信码不正确'];
        } else {
            // 修改Session中短信码状态
            $sms['verify'] = true;
            Session::set('sms',$sms);
            
            return [ 201,[] ];
        }
    }
}